<template>
    <div class="marketing_group_add">
        <el-form label-width="120px" :model="form" :rules="rules" ref="addForm">
            <div class="form_content">
                <el-card class="base_card">
                    <template #header>基础设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item label="活动名称" prop="activityName" class="margin_left_26">
                                <el-input
                                    v-model.trim="form.activityName"
                                    placeholder="请输入活动名称，20个字以内"
                                    maxlength="20"
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item
                                label="活动时间"
                                prop="activityAt"
                                @mouseover="handleMouseover"
                                class="margin_left_26"
                                @mouseleave="handleMouseleave">
                                <el-date-picker
                                    v-model="form.activityAt"
                                    type="datetimerange"
                                    range-separator="至"
                                    :default-time="defaultTime"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :disabled="isDisabled"
                                    :disabled-date="disabledDate" />
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="参团人数" prop="requiredNum" class="margin_left_26">
                                <template v-if="activityType == 5">
                                    <el-form-item
                                        v-for="(item, index) in form.requiredNum"
                                        style="margin-bottom: 20px"
                                        class="requiredNum-form-item"
                                        :key="index"
                                        :prop="'requiredNum' + index"
                                        :rules="requiredRuleNums[index]">
                                        第{{ numText[index] }}阶梯人数
                                        <el-input-number
                                            v-model="form.requiredNum[index]"
                                            :min="2"
                                            :max="100"
                                            :controls="false"
                                            :precision="0"
                                            placeholder="请输入2~100人"
                                            :disabled="isDisabled"
                                            style="margin: 0 4px"
                                            @change="handleVerifyRequiredNum"
                                            @mouseover="handleMouseover"
                                            @mouseleave="handleMouseleave"
                                            class="custom-number" />&nbsp;人
                                        <span v-if="index === 2">
                                            <el-button
                                                type="primary"
                                                :disabled="isDisabled"
                                                text
                                                @click="handleRemoveLadder(index)">
                                                删除
                                            </el-button>
                                        </span>
                                    </el-form-item>
                                    <div style="width: 100%">
                                        <span>
                                            <el-button
                                                :disabled="isDisabled || requiredNum?.length === 3"
                                                @click="handleAddLadder"
                                                >添加拼团阶梯</el-button
                                            >
                                        </span>
                                    </div>
                                </template>
                                <template v-else>
                                    <el-input-number
                                        v-model="form.requiredNum"
                                        :min="2"
                                        :max="100"
                                        :controls="false"
                                        :precision="0"
                                        placeholder="请输入2~100人"
                                        :disabled="isDisabled"
                                        @mouseover="handleMouseover"
                                        @mouseleave="handleMouseleave"
                                        class="custom-number" />&nbsp;人
                                </template>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="拼团商品" prop="goodsId" class="good-form-item margin_left_26">
                                <span @mouseover="handleMouseover" @mouseleave="handleMouseleave">
                                    <!-- <el-button class="good-btn" @click="openChooseGoodHandler" :disabled="isDisabled">
                                        {{ `${form.goodsId ? '重新' : ''}选择商品` }}
                                    </el-button> -->
                                    <ZwGeneralGoods
                                        :disabled="isDisabled"
                                        :isParticipationCol="true"
                                        :isMulti="false"
                                        :value="form.goodsId"
                                        @handle-confirm="getGoodData"></ZwGeneralGoods>
                                </span>
                                <el-table
                                    class="sku-table"
                                    :data="form.goodsSku"
                                    v-if="form.goodsId"
                                    :span-method="skuSpanMethod"
                                    width="800">
                                    <el-table-column label="商品" width="257">
                                        <div class="good-preview">
                                            <el-image
                                                style="width: 36px; height: 36px"
                                                :src="goodInfo.materialSrc"
                                                fit="fill" />
                                            <div>
                                                <h5>{{ selectData.goodsName }}</h5>
                                                <p>{{ selectData.goodsNo }}</p>
                                            </div>
                                        </div>
                                    </el-table-column>
                                    <!-- 阶梯 -->
                                    <template v-if="activityType == 5">
                                        <el-table-column
                                            v-for="{ prop, ...rest } in ladderColumns"
                                            :key="prop"
                                            :prop="prop"
                                            v-bind="rest">
                                            <template v-if="['0', '1', '2'].includes(prop)" #header>
                                                {{ rest.label }}
                                                <el-popover
                                                    :ref="el => setItemRef(el, `popoverRef${prop}`)"
                                                    popper-class="custom-add-popover-class"
                                                    placement="top"
                                                    :width="216"
                                                    trigger="click"
                                                    @hide="popoverLadderHide(prop)">
                                                    <div>
                                                        <el-form
                                                            :ref="el => setItemRef(el, `batchFormRef${prop}`)"
                                                            :model="batchForm"
                                                            label-position="top">
                                                            <el-form-item
                                                                prop="batchGroupPrice"
                                                                :rules="[
                                                                    {
                                                                        required: true,
                                                                        validator: checkBatchLadderPrice(prop),
                                                                        trigger: 'blur'
                                                                    }
                                                                ]"
                                                                label="拼团价：">
                                                                <el-input-number
                                                                    style="width: 100%"
                                                                    v-model="batchForm.batchGroupPrice"
                                                                    :min="0.01"
                                                                    :max="99999"
                                                                    :precision="2"
                                                                    :controls="false"
                                                                    placeholder="请输入"
                                                                    class="custom-number" />
                                                            </el-form-item>
                                                            <div style="text-align: right">
                                                                <el-button
                                                                    size="small"
                                                                    @click="closeLadderPopover(prop)"
                                                                    >取消</el-button
                                                                >
                                                                <el-button
                                                                    type="primary"
                                                                    size="small"
                                                                    @click="batchLadderHandler(prop)"
                                                                    >确定</el-button
                                                                >
                                                            </div>
                                                        </el-form>
                                                    </div>
                                                    <template #reference>
                                                        <span
                                                            @mouseover="handleMouseover"
                                                            @mouseleave="handleMouseleave">
                                                            <el-button size="small" :disabled="isDisabled" :key="prop"
                                                                >批量设置</el-button
                                                            >
                                                        </span>
                                                    </template>
                                                </el-popover>
                                            </template>
                                            <template v-if="['0', '1', '2'].includes(prop)" #default="{ row, $index }">
                                                <!-- todo:index -->
                                                <el-form-item
                                                    class="price-form-item"
                                                    label-width="0px"
                                                    :prop="'goodsSku.' + $index + '.groupPrice.' + prop"
                                                    :rules="[
                                                        {
                                                            required: true,
                                                            validator: checkLadderPrice($index, prop),
                                                            trigger: 'blur'
                                                        }
                                                    ]">
                                                    <el-input-number
                                                        v-model="row.groupPrice[prop]"
                                                        :min="0.01"
                                                        :max="99999"
                                                        :precision="2"
                                                        :controls="false"
                                                        placeholder="请输入"
                                                        :disabled="isDisabled"
                                                        @blur="handleVerifyGroupPrice()"
                                                        @mouseover="handleMouseover"
                                                        @mouseleave="handleMouseleave"
                                                        class="custom-number" />
                                                </el-form-item>
                                            </template>
                                        </el-table-column>
                                    </template>
                                    <!-- 普通，老带新 -->
                                    <template v-else>
                                        <el-table-column
                                            v-for="{ prop, ...rest } in skuTableColumns"
                                            :key="prop"
                                            :prop="prop"
                                            v-bind="rest">
                                            <template v-if="prop === 'groupPrice'" #header>
                                                {{ rest.label }}
                                                <span @mouseover="handleMouseover" @mouseleave="handleMouseleave">
                                                    <el-button size="small" :ref="setButtonRef" :disabled="isDisabled"
                                                        >批量设置</el-button
                                                    >
                                                </span>
                                            </template>
                                            <template v-if="['groupPrice'].includes(prop)" #default="{ row, $index }">
                                                <el-form-item
                                                    class="price-form-item"
                                                    :prop="'goodsSku.' + $index + '.groupPrice'"
                                                    :rules="groupPriceRules">
                                                    <el-input-number
                                                        v-model="row.groupPrice"
                                                        :min="0.01"
                                                        :max="99999"
                                                        :precision="2"
                                                        :controls="false"
                                                        placeholder="请输入"
                                                        :disabled="isDisabled"
                                                        @mouseover="handleMouseover"
                                                        @mouseleave="handleMouseleave"
                                                        class="custom-number" />
                                                </el-form-item>
                                            </template>
                                        </el-table-column>
                                    </template>
                                </el-table>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="拼团有效期" prop="spellGroupExpireAt" class="expire-at margin_left_26">
                                <el-select
                                    class="custom-el-select"
                                    placeholder="请选"
                                    v-model="form.spellGroupExpireAt[0]"
                                    :disabled="isDisabled"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    @change="clearValidate('spellGroupExpireAt')">
                                    <el-option v-for="item in dayList" :key="item" :label="item" :value="item">
                                    </el-option> </el-select
                                ><span>日</span>
                                <el-select
                                    v-model="form.spellGroupExpireAt[1]"
                                    class="custom-el-select"
                                    :disabled="isDisabled"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    @change="clearValidate('spellGroupExpireAt')"
                                    placeholder="请选">
                                    <el-option v-for="item in minutesList" :key="item" :label="item" :value="item">
                                    </el-option> </el-select
                                ><span>时</span>
                                <el-select
                                    class="custom-el-select"
                                    placeholder="请选"
                                    v-model="form.spellGroupExpireAt[2]"
                                    :disabled="isDisabled"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    @change="clearValidate('spellGroupExpireAt')">
                                    <el-option v-for="item in secondsList" :key="item" :label="item" :value="item">
                                        {{ item }}
                                    </el-option> </el-select
                                ><span>分</span>
                                <div class="custom-tip">
                                    拼团有效期最短15分钟，最长30天，若设置1日，则用户开团后需在1天（24小时）内成团，超时未成团拼团失败。
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card>
                    <template #header>高级设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item
                                v-for="{ label, checkboxLabel, prop, tip } in advancedList"
                                :label="label"
                                :prop="prop"
                                class="margin_left_26"
                                :key="label">
                                <div v-if="prop === 'purchaseRule'">
                                    <el-checkbox
                                        v-model="form[prop]"
                                        :true-label="2"
                                        :false-label="1"
                                        :disabled="isDisabled"
                                        @mouseover="handleMouseover"
                                        @mouseleave="handleMouseleave"
                                        @change="handlePurChange"
                                        >{{ checkboxLabel }}</el-checkbox
                                    >
                                    <div v-if="form[prop] == 2">
                                        <div
                                            v-for="{ prop, inputProp, checkboxLabel } in purchaseRuleList"
                                            :key="prop"
                                            class="rule-checkbox">
                                            <el-checkbox
                                                v-model="purchaseCheckbox[prop]"
                                                :true-label="2"
                                                :false-label="1"
                                                :disabled="isDisabled"
                                                @change="handleLimitChange($event, prop)"
                                                >活动每{{ checkboxLabel }}限购</el-checkbox
                                            >
                                            <el-input-number
                                                v-model="form[inputProp]"
                                                :disabled="purchaseCheckbox[prop] == 1 || isDisabled"
                                                :max="9999"
                                                :precision="0"
                                                :controls="false"
                                                placeholder="请输入"
                                                @mouseover="handleMouseover"
                                                @mouseleave="handleMouseleave"
                                                class="custom-number" />件
                                        </div>
                                    </div>
                                </div>
                                <el-checkbox
                                    v-else
                                    v-model="form[prop]"
                                    :true-label="2"
                                    :false-label="1"
                                    :disabled="isDisabled"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    >{{ checkboxLabel }}</el-checkbox
                                >
                                <div v-if="tip" class="custom-tip" v-html="tip"></div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="form-footer">
                <div>
                    <el-button @click="cancelHandler">取消</el-button>
                    <el-button type="primary" @click="saveHandler">保存</el-button>
                </div>
            </div>
        </el-form>
        <!-- popover弹窗 -->
        <el-popover
            width="216px"
            v-if="buttonRef.length"
            popper-class="custom-add-popover-class"
            ref="popoverRef"
            :virtual-ref="buttonRef[0] || buttonRef[1] || buttonRef[2]"
            placement="top"
            trigger="click"
            virtual-triggering
            @hide="popoverHide">
            <div>
                <el-form ref="batchFormRef" :model="batchForm" label-position="top">
                    <el-form-item prop="batchGroupPrice" :rules="batchGroupPriceRules" label="拼团价：">
                        <el-input-number
                            style="width: 100%"
                            v-model="batchForm.batchGroupPrice"
                            :min="0.01"
                            :max="99999"
                            :precision="2"
                            :controls="false"
                            placeholder="请输入"
                            class="custom-number" />
                    </el-form-item>
                    <div style="text-align: right">
                        <el-button size="small" @click="closeBatchPopover">取消</el-button>
                        <el-button type="primary" size="small" @click="batchPriceHandler">确定</el-button>
                    </div>
                </el-form>
            </div>
        </el-popover>
        <!-- tooltip提示框 -->
        <el-tooltip
            popper-class="custom-tooltip-class"
            v-model:visible="tooltipVisible"
            content="活动已开始，不支持编辑"
            placement="top"
            trigger="click"
            virtual-triggering
            :virtual-ref="triggerRef" />
    </div>
</template>

<script setup>
import { ref, unref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/request/index';
import { ElMessage } from 'element-plus';
import { isDayBefore, dateDiff, cloneDeep, format, isEmpty } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';

const router = useRouter();
const route = useRoute();

const addForm = ref(null);
let buttonRef = reactive([]);
const popoverRef = ref(null);
const batchFormRef = ref(null);
const position = ref({
    top: 0,
    left: 0,
    bottom: 0,
    right: 0
});
const triggerRef = ref({
    getBoundingClientRect() {
        return position.value;
    }
});
let tooltipVisible = ref(false);

const form = reactive({
    activityName: '', // 活动名
    activityAt: [], // 开始结束时间
    requiredNum: null, //参团人数
    goodsId: null, //拼团商品id
    goodsSku: [], // 规格
    spellGroupExpireAt: ['00', '00', '00'], // 拼团有效期
    discountRepeat: null, //叠加优惠 1-不叠加 2-叠加
    spellGroupMail: null, //拼团包邮 1-不包邮 2-包邮
    purchaseRule: null, //限购规则 1-不限购 2-限购
    purchaseLimit: null, //每人限购数量
    orderPurchaseLimit: null, //每单限购数量
    gatherGroup: 2, //凑团 1-不凑团 2-凑团
    simulateGroup: null, //模拟成团 1-不模拟 2-模拟
    forecast: null //拼团预告 1-不开启 2-开启
});
const batchForm = reactive({
    batchGroupPrice: null
});
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const disabledDate = date => {
    return isDayBefore(date);
};
const checkGoods = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请选择商品'));
    }
    callback();
};
const checkExpireAt = (rule, value, callback) => {
    if (!value || (value[0] == 0 && value[1] == 0 && value[2] == 0)) {
        return callback(new Error('拼团有效期需在15分钟至30天之内'));
    }
    if (value[0] == 30 && (value[1] > 0 || value[2] > 0)) {
        return callback(new Error('拼团有效期需在15分钟至30天之内'));
    }
    if (value[0] == 0 && value[1] == 0 && value[2] < 15) {
        return callback(new Error('拼团有效期需在15分钟至30天之内'));
    }
    const secondDiff = dateDiff(form.activityAt[1], form.activityAt[0], 's', true);
    const seconds = value[0] * 24 * 60 * 60 + value[1] * 60 * 60 + value[2] * 60;
    if (seconds > secondDiff) {
        return callback(new Error('拼团有效期需小于活动周期'));
    }
    callback();
};
const checkGroupPrice = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请输入拼团价'));
    }
    const { skuPrice } = form.goodsSku[rule.field.split('.')[1]];
    if (value >= skuPrice) {
        return callback(new Error('拼团价需要低于售价'));
    }
    callback();
};
const checkPurchase = (rule, value, callback) => {
    if (value == 1) {
        return callback();
    }
    if (value) {
        if (!form.purchaseLimit && !form.orderPurchaseLimit) {
            if (form.purchaseLimit === null && form.orderPurchaseLimit === null) {
                return callback(new Error('请至少选择输入一项限制'));
            }
            if (form.purchaseLimit === 0) {
                return callback(new Error('每人限购数量必须大于0'));
            }
            if (form.orderPurchaseLimit === 0) {
                return callback(new Error('每单限购数量必须大于0'));
            }
            return callback(new Error('请至少选择输入一项限制'));
        }
        if (purchaseCheckbox.purchase == 2 && !form.purchaseLimit) {
            if (form.purchaseLimit == 0) {
                return callback(new Error('每人限购数量必须大于0'));
            }
            return callback(new Error('请输入每人限购'));
        }
        if (purchaseCheckbox.orderPurchase == 2 && !form.orderPurchaseLimit) {
            if (form.orderPurchaseLimit == 0) {
                return callback(new Error('每单限购数量必须大于0'));
            }
            return callback(new Error('请输入每单限购'));
        }
        if (form.purchaseLimit && form.orderPurchaseLimit && form.purchaseLimit < form.orderPurchaseLimit) {
            return callback(new Error('每人限购数量不能小于每单限购数量'));
        }
    }
    callback();
};
const checkActivityAt = (rule, value, callback) => {
    if (!value || !value[0]) {
        return callback(new Error('请选择活动时间'));
    }
    if (value) {
        const currentDate = new Date();
        if (value[0] < currentDate) {
            return callback(new Error('活动时间不能早于当前时间'));
        }
    }
    callback();
};
const batchCheckGroupPrice = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请输入拼团价'));
    }
    const minSkuPrice = Math.min(form.goodsSku.map(item => item.skuPrice));
    if (value > minSkuPrice) {
        return callback(new Error('拼团价不能大于售价'));
    }
    callback();
};
const requiredNum = reactive([null, null]);
const checkRequiredNum = (rule, value, callback) => {
    if (isEmpty(requiredNum)) {
        return callback('请添加拼团阶梯');
    }
    return callback();
};
const checkIndexNum = index => {
    const required = (rule, value, callback) => {
        if (!requiredNum[index]) {
            return callback('请填写阶梯人数');
        }
        if (index !== 0 && requiredNum[index - 1] >= requiredNum[index]) {
            return callback('人数需大于上一阶梯');
        }
        callback();
    };
    return required;
};
const checkLadderPrice = (index, prop) => {
    const required = (rule, value, callback) => {
        if (!value) {
            return callback('请设置拼团价格');
        }
        const goodPrice = form?.goodsSku?.[index]?.skuPrice;
        if (value >= goodPrice) {
            return callback('拼团价不能大于售价');
        }
        const prevVal = form?.goodsSku?.[index]?.groupPrice?.[prop - 1];
        if (prop != 0 && value >= prevVal) {
            return callback('价格需小于上一阶梯');
        }
        callback();
    };
    return required;
};
const checkBatchLadderPrice = prop => {
    const required = (rule, value, callback) => {
        if (!value) {
            return callback('请设置拼团价格');
        }
        const minSkuPrice = Math.min(form.goodsSku.map(item => item.skuPrice));
        if (value > minSkuPrice) {
            return callback(new Error('拼团价不能大于售价'));
        }
        const prevVal = Math.min(form.goodsSku.map(item => item?.groupPrice?.[prop - 1]));
        if (prop != 0 && value >= prevVal) {
            return callback('价格需小于上一阶梯');
        }
        callback();
    };
    return required;
};
const rules = computed(() => {
    const baseRuleList = {
        activityName: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { max: 20, message: '最长不超过20个字', trigger: 'blur' }
        ],
        activityAt: [{ required: true, trigger: 'change', validator: checkActivityAt }],
        goodsId: [{ required: true, validator: checkGoods, trigger: 'change' }],
        spellGroupExpireAt: [{ required: true, validator: checkExpireAt, trigger: 'change' }]
    };
    const purchaseRule =
        form.purchaseRule === 2 ? [{ required: true, validator: checkPurchase, trigger: 'change' }] : null;
    if (activityType.value == 5) {
        baseRuleList.requiredNum = [{ required: true, validator: checkRequiredNum }];
    } else {
        baseRuleList.requiredNum = [{ required: true, message: '请输入参团人数', trigger: 'blur' }];
    }
    return { ...baseRuleList, purchaseRule };
});
const groupPriceRules = reactive([{ required: true, validator: checkGroupPrice, trigger: 'blur' }]);
const batchGroupPriceRules = reactive([{ required: true, validator: batchCheckGroupPrice, trigger: 'blur' }]);
const requiredRuleNums = computed(() => {
    return requiredNum.map((item, index) => [{ required: true, validator: checkIndexNum(index), trigger: 'blur' }]);
});

let selectData = reactive([]);
const skuTableColumns = reactive([
    { label: '规格', prop: 'specs', width: '159' },
    { label: '售价（元）', prop: 'skuPriceText', width: '160' },
    { label: '拼团价（元）', prop: 'groupPrice', width: '223', fixed: 'right' }
]);
const ladderColumns = computed(() => {
    const baseCols = [
        { label: '规格', prop: 'specs', minWidth: '159' },
        { label: '售价（元）', prop: 'skuPriceText', minWidth: '160', fixed: 'right' }
    ];
    const otherCols = requiredNum
        // .filter(item => Boolean(item))
        .map((item, index) => {
            return { label: (item || 0) + '人拼团价（元）', prop: `${index}`, width: '223', fixed: 'right' };
        });
    return [...baseCols, ...otherCols];
});

const goodInfo = reactive({
    materialSrc: null
});
const getTimeList = total => {
    return new Array(total).fill(null).map((item, i) => {
        return `${i < 10 ? 0 : ''}${i}`;
    });
};
const dayList = getTimeList(31); // 天数
const minutesList = getTimeList(24); // 分
const secondsList = getTimeList(60); // 分
const advancedList = [
    { label: '优惠叠加', checkboxLabel: '允许叠加使用优惠券', prop: 'discountRepeat' },
    { label: '拼团包邮', checkboxLabel: '开启拼团包邮', prop: 'spellGroupMail' },
    { label: '限购规则', checkboxLabel: '开启限购', prop: 'purchaseRule' },
    {
        label: '凑团',
        checkboxLabel: '开启凑团',
        prop: 'gatherGroup',
        tip: '开启凑团后，商品详情页展示未成团的团列表，买家可任意选择一个团参团，提升参团率。'
    },
    {
        label: '模拟成团',
        checkboxLabel: '开启模拟成团',
        prop: 'simulateGroup',
        tip: '开启模拟成团后，系统将会在拼团结束前10分钟模拟“<span style="color: #33302d">匿名买家</span>”凑满该团，仅需对真实买家发货。建议合理开启，以提高成团率。'
    }
];

/* --------------------------------- 添加阶梯拼团 start --------------------------------- */
const numText = reactive(['一', '二', '三']);
const handleAddLadder = () => {
    // 添加阶梯拼团
    requiredNum.push(null);
    form.requiredNum = [];
    form.requiredNum = requiredNum;
    validateField('requiredNum');
};
const handleRemoveLadder = index => {
    // 删除阶梯拼团
    requiredNum.splice(index, 1);
    form.goodsSku = form.goodsSku.map(item => {
        item.groupPrice.splice(index, 1);
        return item;
    });
    form.requiredNum = [];
    form.requiredNum = requiredNum;
    validateField('requiredNum');
};
const handleVerifyRequiredNum = () => {
    // 失去焦点校验参团人数
    form.requiredNum.forEach((item, index) => {
        validateField(`requiredNum${index}`);
    });
};
const handleVerifyGroupPrice = () => {
    // 失去焦点校验参多人拼团
    form.goodsSku.forEach((item, index) => {
        item.groupPrice.forEach((item, prop) => {
            validateField('goodsSku.' + index + '.groupPrice.' + prop);
        });
    });
};
/* --------------------------------- 添加阶梯拼团 end --------------------------------- */
const purchaseCheckbox = reactive({
    orderPurchase: 1,
    purchase: 1
});
const purchaseRuleList = [
    { checkboxLabel: '单', prop: 'orderPurchase', inputProp: 'orderPurchaseLimit' },
    { checkboxLabel: '人', prop: 'purchase', inputProp: 'purchaseLimit' }
];

const isDisabled = computed(() => {
    const realStatus = form?.activityStatusName?.realStatus;
    return realStatus && realStatus != 1;
});
const id = computed(() => {
    return route?.query?.id;
});
const activityType = computed(() => {
    const path = route?.path;
    if (/new/.test(path)) {
        return 4;
    }
    if (/ladder/.test(path)) {
        return 5;
    }
    return 3;
});

if (activityType.value == 5) {
    form.requiredNum = requiredNum;
}

// 普通老带新批量
const setButtonRef = el => {
    buttonRef.length = 0;
    buttonRef.push(el);
};
const batchPriceHandler = async () => {
    await batchFormRef.value.validate((valid, fields) => {
        if (valid) {
            form.goodsSku = form.goodsSku.map((item, i) => {
                clearValidate(`goodsSku.${i}.groupPrice`);
                item.groupPrice = batchForm.batchGroupPrice;
                return item;
            });
            closeBatchPopover();
        }
    });
};
const popoverHide = () => {
    unref(batchFormRef).clearValidate('batchGroupPrice');
    batchForm.batchGroupPrice = null;
};
const closeBatchPopover = () => {
    unref(popoverRef)?.hide?.();
};
// 阶梯
const itemRefs = reactive({});
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const closeLadderPopover = prop => {
    itemRefs['popoverRef' + prop]?.hide?.();
};
const batchLadderHandler = async prop => {
    await itemRefs['batchFormRef' + prop].validate((valid, fields) => {
        if (valid) {
            form.goodsSku = form.goodsSku.map((item, i) => {
                clearValidate(`goodsSku.${i}.groupPrice.${prop}`);
                item.groupPrice[prop] = batchForm.batchGroupPrice;
                return item;
            });
            closeLadderPopover(prop);
        }
    });
};
const popoverLadderHide = prop => {
    itemRefs['batchFormRef' + prop].clearValidate('batchGroupPrice');
    batchForm.batchGroupPrice = null;
};

const skuSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 0) {
        if (rowIndex === 0) {
            return {
                rowspan: form.goodsSku.length,
                colspan: 1
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0
            };
        }
    } else {
        return {
            rowspan: 1,
            colspan: 1
        };
    }
};
const handlePurChange = (val, prop) => {
    if (val == 1) {
        form.purchaseLimit = null;
        form.orderPurchaseLimit = null;
        purchaseCheckbox.orderPurchase = 1;
        purchaseCheckbox.purchase = 1;
    }
    clearValidate('purchaseRule');
};
const handleLimitChange = (val, prop) => {
    if (val == 1) {
        form[`${prop}Limit`] = null;
    }
};
const cancelHandler = () => {
    // router.push({ path: '/marketing/group' });
    router.back();
};
const clearValidate = field => {
    unref(addForm).clearValidate(field);
};
const validateField = field => {
    unref(addForm).validateField(field);
};
const getGoodData = data => {
    Object.assign(selectData, data);
    form.goodsId = selectData.id;
    goodInfo.materialSrc = selectData?.materialSrc?.[0]?.materialSrc;
    const skuInfo = selectData.skuInfo.map(item => {
        item.skuPrice = item.skuPrice / 100;
        item.skuPriceText = `¥ ${item.skuPrice}`;
        if (activityType.value == 5) {
            item.groupPrice = requiredNum.map(item => null);
        } else {
            item.groupPrice = null;
        }
        item.specs = item.specs.join();
        return item;
    });
    form.goodsSku.length = 0;
    Object.assign(form.goodsSku, skuInfo);
    clearValidate('goodsId');
};
const handleMouseover = e => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = true;
    position.value = DOMRect.fromRect({
        width: 0,
        height: 0,
        x: e.clientX,
        y: e.clientY
    });
};
const handleMouseleave = el => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = false;
    position.value = {
        top: 0,
        left: 0,
        bottom: 0,
        right: 0
    };
};
// 新增/编辑表单
const saveHandler = async () => {
    if (!unref(addForm)) return;
    await unref(addForm).validate(async (valid, fields) => {
        if (valid) {
            const _form = cloneDeep(form);
            _form.activityType = activityType.value;
            _form.activityStartTime = format(_form.activityAt[0], 'YYYY-MM-DD HH:mm:ss');
            _form.activityEndTime = format(_form.activityAt[1], 'YYYY-MM-DD HH:mm:ss');
            delete _form.activityAt;
            if (_form.purchaseRule == 1) {
                _form.purchaseLimit = 0;
                _form.orderPurchaseLimit = 0;
            }
            if (purchaseCheckbox.orderPurchase == 1) {
                _form.orderPurchaseLimit = 0;
            }
            if (purchaseCheckbox.purchase == 1) {
                _form.purchaseLimit = 0;
            }
            if (activityType.value == 5) {
                _form.requiredNum = requiredNum;
            } else {
                _form.requiredNum = [_form.requiredNum];
            }
            _form.goodsSku = _form.goodsSku.map(item => {
                const { id: skuId, specs: skuName, skuPrice, groupPrice } = item;
                return {
                    skuId,
                    skuName,
                    skuPrice: Math.round(skuPrice * 100),
                    groupPrice:
                        activityType.value == 5
                            ? groupPrice?.map(item => Math.round(item * 100))
                            : [Math.round(groupPrice * 100)]
                };
            });
            const { code } = await request(`spellGroup${unref(id) ? 'Edit' : 'Create'}`, _form);
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '拼团活动保存成功'
            });
            cancelHandler();
        } else {
            unref(addForm).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const getDetail = async () => {
    if (unref(id)) {
        const { data } = await request('spellGroupInfo', { id: unref(id) });
        data.activityAt = [data.activityStartTime, data.activityEndTime];
        data.goodsSku = data.skuInfo.map(item => {
            let { id, specs, skuPrice, groupPrice } = item;
            return {
                id,
                specs: specs.join(),
                skuPrice: skuPrice / 100,
                skuPriceText: `¥ ${skuPrice / 100}`,
                groupPrice: activityType.value == 5 ? groupPrice?.map(item => item / 100) : groupPrice[0] / 100
            };
        });
        if (data.purchaseRule == 1) {
            data.orderPurchaseLimit = null;
            data.purchaseLimit = null;
        } else {
            data.orderPurchaseLimit = data.orderPurchaseLimit || null;
            data.purchaseLimit = data.purchaseLimit || null;
        }
        if (data.orderPurchaseLimit) {
            purchaseCheckbox.orderPurchase = 2;
        }
        if (data.purchaseLimit) {
            purchaseCheckbox.purchase = 2;
        }
        if (activityType.value == 5) {
            Object.assign(requiredNum, data.requiredNum);
        } else {
            data.requiredNum = data.requiredNum[0];
        }
        Object.assign(form, data);
        goodInfo.materialSrc = data.goods.img;
        const { name: goodsName, goodsNo } = data.goods;
        Object.assign(selectData, { goodsName, goodsNo });
    }
};

onMounted(() => {
    getDetail();
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
.custom-add-popover-class {
    .el-input-number .el-input__inner {
        text-align: left;
    }
}
.requiredNum-form-item {
    .el-form-item__error {
        top: 110%;
        left: 90px;
    }
}
.sku-table {
    margin-top: 16px;
    border: 1px solid #eaeaea;
    tbody tr:first-of-type {
        td:first-of-type {
            border-right: 1px solid #eaeaea;
        }
    }
    .good-preview {
        display: flex;
        align-items: center;
        & > div {
            &:first-of-type {
                margin-right: 8px;
                min-width: 36px;
            }
            &:last-of-type {
                display: flex;
                justify-content: center;
                flex-direction: column;
            }
        }
        h5,
        p {
            margin: 0;
        }
        h5 {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
        }
        p {
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #969696;
        }
    }
}
.custom-tooltip-class {
    padding: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    /* color: #33302d; */
}
</style>
<style lang="scss" scoped>
.marketing_group_add {
    position: relative;
    min-height: calc(100vh - 190px);
    .margin_left_26 {
        margin-left: -26px;
    }
    .base_card {
        margin-bottom: 16px;
        :deep(.el-form-item__content) {
            max-width: 400px;
        }
        .expire-at:deep(.el-form-item__content) {
            max-width: initial;
        }
    }
    .sku-table {
        width: auto;
    }
    .good-form-item {
        :deep(> .el-form-item__content) {
            max-width: 1400px;
            width: 90%;
            min-width: 800px;
            flex-direction: column;
            align-items: flex-start;
        }
    }
    .form_content {
        overflow-y: auto;
        max-height: calc(100vh - 210px);
        :deep(.el-card) {
            border: none;
            border-radius: 0;
            box-shadow: none;
            .el-card__header,
            .el-card__body {
                padding-left: 24px;
            }
        }
    }

    .custom-el-select {
        width: 75px;
        & + span {
            margin: 0 5px;
        }
    }

    :deep .el-input-number .el-input__inner {
        text-align: left;
    }

    .price-form-item {
        margin: 20px 0;
        :deep(.el-form-item__label-wrap) {
            margin-left: 0 !important;
        }
    }

    .custom-tip {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        width: 100%;
    }

    .rule-checkbox {
        &:last-of-type {
            margin-top: 16px;
        }
        .el-checkbox {
            margin-right: 5px;
        }
        :deep(.el-input-number) {
            width: 90px;
            margin-right: 5px;
        }
    }

    .form-footer {
        position: absolute;
        bottom: -64px;
        left: -15px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% + 31px);
        height: 70px;
        background-color: #fff;
        box-shadow: 0px 0px 10px 0px rgb(212 212 212 / 50%);
        border-radius: 2px;
        & > div {
            /* margin-left: -160px; */
        }
        .el-button {
            width: 80px;
        }
    }

    .el-button.is-disabled,
    .el-button.is-disabled:hover,
    .el-button.is-disabled:focus {
        background-color: var(--el-disabled-bg-color);
    }
}
</style>
